package caras;

import java.awt.image.BufferedImage;

public class downloadMosaicImage {
	
	protected static BufferedImage imagen ;
	protected static int downSampleLeft;
	protected static int downSampleRight;
	protected static int downSampleTop;
	protected static int downSampleBottom;
	protected static double ratioX;
	protected static double ratioY;
	protected static int[] pixelMap;
	protected static int anchoRejilla;
	protected static int altoRejilla;
	public String imagenString=null;
	
	
	public downloadMosaicImage(final BufferedImage imagenOrigen,final int ancho ,final int alto  ) {
		
	    imagen=imagenOrigen;
		altoRejilla=alto;
		anchoRejilla=ancho;
		
		imagenString=getImage2String();
		
		
	}

	
	protected static boolean hLineClear(int y) {
		int w = imagen.getWidth(null);
		for (int i = 0; i < w; i++) {
			if (pixelMap[(y * w) + i] != -1)
				return false;
		}
		return true;
	}

	protected static boolean vLineClear(int x) {
		int w = imagen.getWidth(null);
		int h = imagen.getHeight(null);
		for (int i = 0; i < h; i++) {
			if (pixelMap[(i * w) + x] != -1)
				return false;
		}
		return true;
	}

	protected static void findBounds(int w, int h) {
		// top line
		for (int y = 0; y < h; y++) {
			if (!hLineClear(y)) {
				downSampleTop = y;
				break;
			}

		}
		// bottom line
		for (int y = h - 1; y >= 0; y--) {
			if (!hLineClear(y)) {
				downSampleBottom = y;
				break;
			}
		}
		// left line
		for (int x = 0; x < w; x++) {
			if (!vLineClear(x)) {
				downSampleLeft = x;
				break;
			}
		}

		// right line
		for (int x = w - 1; x >= 0; x--) {
			if (!vLineClear(x)) {
				downSampleRight = x;
				break;
			}
		}
	}

	protected static boolean downSampleQuadrant(int x, int y) {
		int w = imagen.getWidth(null);
		int startX = (int) (downSampleLeft + (x * ratioX));
		int startY = (int) (downSampleTop + (y * ratioY));
		int endX = (int) (startX + ratioX);
		int endY = (int) (startY + ratioY);

		for (int yy = startY; yy <= endY; yy++) {
			for (int xx = startX; xx <= endX; xx++) {
				int loc = xx + (yy * w);

				if (pixelMap[loc] != -1)
					return true;
			}
		}

		return false;
	}
	
	protected static String getImage2String() {
		
		int w = imagen.getWidth(null);
		int h = imagen.getHeight(null);
		
		String imagenString="";
		
		pixelMap = new int[w * h];

		imagen.getRGB(0, 0, w, h, pixelMap, 0, w);

		findBounds(w, h);

		ratioX = (double) (downSampleRight - downSampleLeft)
				/ (double) anchoRejilla;
		ratioY = (double) (downSampleBottom - downSampleTop)
				/ (double) altoRejilla;

		for (int y = 0; y < altoRejilla; y++) {
			for (int x = 0; x < anchoRejilla; x++) {
				if (downSampleQuadrant(x, y)) {
					imagenString = imagenString + "1;";
				} else {
					imagenString = imagenString + "0;";
				}
			}

		}
		
		return (imagenString);
		
	}
}
